package com.bt.lms.ui.action.registration.stu;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.BOConstant;

import com.bt.lms.constants.RegStuBizTypeConstant;
import com.bt.lms.entity.RegStuInfo;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.packet.ReqMsgPacket;
import com.bt.lms.ui.page.stu.vo.RegistrationStuVo;
import com.bt.lms.utils.Convert;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

/**
 * 主界面删除按钮事件
 */
public class PageMainStuDeleteBtnAction implements EventHandler {

    @Override

    public void handle(Event event) {


        //报名学员信息

        RegStuInfo regStuInfo = new RegStuInfo();


        //1.组包

        byte[]bytes = handleReqMsg(regStuInfo);

        //4.组网
        Socket socket = getNet();
        //5.发送消息
        boolean flag = sendReq(socket, bytes);


        //删除提示框
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setContentText("你确定删除吗?");
        alert.show();


    }

    /**
     * 发送消息
     *
     * @param socket       网络
     * @param bytes  byte 数组
     * @return 是否成功
     */
    private boolean sendReq(Socket socket, byte[]bytes) {


        try {
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush();


        } catch (IOException e) {
//            throw new RuntimeException(e);
        }


        return true;
    }

    /**
     * 组网
     *
     * @return 网络
     */
    private Socket getNet() {
        String serverIP = "127.0.0.1";
        int serverPort = 8888;
        Socket socket = null;
        try {
            socket = new Socket(serverIP, serverPort);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return null;
        }
        return socket;
    }





    /**
     * 组包
     * @param regStuInfo 报名学员信息
     * @return 消息
     */
    private byte[] handleReqMsg(RegStuInfo regStuInfo) {



        //消息
        ReqMsg reqMsg = new ReqMsg();

        RegistrationStuVo registrationStuVo = new RegistrationStuVo();


        //业务类型  删除功能4004
        reqMsg.setBizType(RegStuBizTypeConstant.STU_REG_INFO_DELETE);

        //请求id时间戳
        long l = System.currentTimeMillis();
        reqMsg.setReqId(l);


        try {
            BeanUtils.copyProperties(regStuInfo,registrationStuVo);

            String regStuStr = JSON.toJSONString(regStuInfo);

            reqMsg.setData(regStuStr);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        byte[] bytes = reqMsg.toBytes();


        return bytes;


    }


}
